package lucene.server.web.dao;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import lombok.SneakyThrows;
import lucene.server.common.model.TaskConfig;
import lucene.server.common.utils.CronUtil;
import lucene.server.common.utils.StringUtil;
import lucene.server.core.model.FieldConfig;
import lucene.server.core.model.IndexConfig;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class IndexConfigDao {

    @SneakyThrows
    public static long countByCon(String connName)  {
        return Db.use().count(Entity.create("index_config").set("conn", connName));
    }
    @SneakyThrows
    public static IndexConfig getByName(String indexName) throws SQLException {
        Entity entity = Db.use().get(Entity.create("index_config").set("name", indexName));
        if (entity == null || entity.isEmpty()){
            return null;
        }else {
            return entity.toBean(IndexConfig.class);
        }
    }
    @SneakyThrows
    public static TaskConfig getIndexRebuildTask(String indexName) throws SQLException {
        Entity entity = Db.use().get(Entity.create("task").set("indexName", indexName).set("type", "REBUILD"));
        if (entity == null || entity.isEmpty()){
            return null;
        }else {
           return entity.toBean(TaskConfig.class);
        }
    }
    @SneakyThrows
    public static void insertIndex(IndexConfig indexConfig) {
        Db.use().tx(db -> {
            Entity entity = Entity.create("index_config").parseBean(indexConfig);
            entity.remove("fieldsConfig");
            if (entity.get("id") == null ){
                entity.set("id", UUID.randomUUID().toString().replace("-", ""));
                db.insert(entity);
            }else{
                db.update(entity,Entity.create().set("id",entity.get("id")));
            }
            List<Entity> list = new ArrayList<>();
            indexConfig.getFieldsConfig().forEach(fieldConfig -> {
                fieldConfig.setIndexName(indexConfig.getName());
                Entity entityField = Entity.create("index_field").parseBean(fieldConfig);
                entityField.set("id", UUID.randomUUID().toString().replace("-", ""));
                entityField.remove("handler");
                list.add(entityField);
            });

            //删除已经存在field配置
            db.del(
                    Entity.create("index_field")
                            .set("indexName", indexConfig.getName())
            );
            db.insert(list);
        });
    }
    @SneakyThrows
    public static void deleteIndex(IndexConfig indexConfig) {
        Db.use().tx(db -> {
            db.del(Entity.create("index_config").set("id", indexConfig.getId()));
            //删除已经存在field配置
            db.del(
                    Entity.create("index_field")
                            .set("indexName", indexConfig.getName())
            );
        });
    }

    @SneakyThrows
    public static List<FieldConfig> getFields(IndexConfig indexConfig){
        return Db.use().findAll(Entity.create("index_field").set("indexName",indexConfig.getName()),FieldConfig.class);
    }

    public static String checkConfig(IndexConfig indexConfig){
        String error = "";
        error += StringUtil.assertNull(indexConfig.getName(),"索引名称不能为空\n");
        error += StringUtil.assertNull(indexConfig.getConn(),"数据库不能为空\n");
        error += StringUtil.assertNull(indexConfig.getTable(),"数据表不能为空\n");
        error += StringUtil.assertNull(indexConfig.getKey(),"关键字段不能为空\n");
        if(StringUtil.isNotEmpty(indexConfig.getCron())){
            try {
                CronUtil.translateToChinese(indexConfig.getCron());
            }catch (Exception e){
                error += e.getMessage()+"\n";
            }
        }
        for (FieldConfig item : indexConfig.getFieldsConfig()){

            error += checkField(item);
        }
        return error;
    }
    public static String checkField(FieldConfig item){
        String itemError = "";
        itemError += StringUtil.assertNull(item.getFieldName(),"字段配置名称不能为空\n");
        itemError += StringUtil.assertNull(item.getTypeName(),"字段配置字段属性不能为空\n");
        return itemError;
    }


}
